/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 *
 */

/*
 * Created by Nabeel Ali Memon (blog:http://www.nabeelalimemon.com/)
 *
 */
package fr.dr.monitor.aspects;

import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;


@Component
@Aspect
public class LoggingAspect {
  //Pointcut definition for all repository transactions that get entities
  @Pointcut("execution(* com.springhibernate.integration.repository.*.get*(..))")
  public void getterTransaction() {}

  //Pointcut definition for all repository transactions that add entities
  @Pointcut("execution(* com.springhibernate.integration.repository.*.add*(..))")
  public void adderTransaction() {}

  //For common Advice on both Pointcuts we combine them to make a single Pointcut
  @Pointcut("adderTransaction() || getterTransaction()")
  public void adderOrGetterTransaction() {}

  //Advice that executes before an Adder or Getter Transaction Join Point is called
  @Before("adderOrGetterTransaction()")
  public void beforeTransaction() {
    System.out.println("------------------------------------");
    System.out.println("--------Beginning transaction-------");
    System.out.println("------------------------------------");
  }

  @AfterThrowing(pointcut = "adderOrGetterTransaction()", throwing = "throwable")
  public void adderOrGetterThrewException(Throwable throwable) {
    throw new RuntimeException("Transaction Unsuccessful. "+throwable.getMessage());
  }
  //Advice that executes after an Adder Transaction Join Point is executed
  @After("adderTransaction()")
  public void afterAdderTransaction() {
    System.out.println("-------Ending Adder Transaction-----");
  }

  //Advice that executes after a Getter Transaction Join Point is executed
  @AfterReturning(pointcut = "getterTransaction()", returning = "retVal")
  public void afterGetterTransaction(Object retVal) {
    System.out.println("Transaction returned value: "+ retVal.toString());
  }
}
